package io.renren.modules.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.modules.sys.entity.*;

import io.renren.modules.sys.service.*;
import net.sf.json.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.swing.filechooser.FileSystemView;
import java.io.File;
import java.io.FileOutputStream;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;


/**
 * 
 *
 * @author Mark
 * @email sunlightcs@gmail.com
 * @date 2019-03-26 14:49:17
 */
@RestController
@RequestMapping("sys/intelreplen")
public class IntelReplenController {
    @Autowired
    private IntelReplenService intelreplenService;

    @Autowired
    private GoodshelvesService goodshelvesService;

    @Autowired
    private ProductshelvesstcokService productshelvesstcokService;

    @Autowired
    private OnshelvesService onshelvesService;

    @Autowired
    private OnshelvesitemService onnshelvesitemService;

    @Autowired
    private ProductService productService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("sys:intelreplen:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = intelreplenService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("sys:intelreplen:info")
    public R info(@PathVariable("id") Integer id){
        IntelReplenEntity intelreplen = intelreplenService.getById(id);

        return R.ok().put("intelreplen", intelreplen);
    }


    /**
     * 统计信息
     */
    @RequestMapping("/infoStatistics")
    @RequiresPermissions("sys:intelreplen:infoStatistics")
    public R infoStatistics(@RequestParam Map<String, Object> params){
        IntelReplenVOEntity intelreplen = intelreplenService.getStatistics(params);

        return R.ok().put("intelreplen", intelreplen);
    }


    /**
     * 补货生成上架信息
     */
    @RequestMapping("/onShelves")
    @RequiresPermissions("sys:intelreplen:onShelves")
    public R onShelves(@RequestBody String parameterMap){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        SysUserEntity user = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
        JSONObject json = JSONObject.fromObject(parameterMap);
        String name = null;
        if(json.get("name")!=null&&!json.get("name").equals("null")){
            name = json.get("name").toString();
        }
        String categoryid = null;
        if(json.get("categoryid")!=null&&!json.get("categoryid").equals("null")){
            categoryid = json.get("categoryid").toString();
        }
        Integer shelvesid = 0;
        if(json.get("shelvesid")!=null&&!json.get("shelvesid").equals("null")){
            shelvesid = Integer.parseInt(json.get("shelvesid").toString());
        }

        List<GoodshelvesEntity> gslist = goodshelvesService.list(new QueryWrapper<GoodshelvesEntity>());
        List<IntelReplenEntity> rows = intelreplenService.queryList(name,categoryid,shelvesid);
        if(gslist.size()>0 &&rows.size()>0){
            for(GoodshelvesEntity gs:gslist){
                OnshelvesEntity onshelvesEntity = new OnshelvesEntity();

                onshelvesEntity.setUppernumber("SJ"+sdf.format(new Date()));
                onshelvesEntity.setShelvesid(gs.getId());
               // onshelvesEntity.setType(arrayProduct.size());
                onshelvesEntity.setCreatetime(new Date());
                onshelvesEntity.setLasttime(new Date());
                onshelvesEntity.setCreateuser(Integer.parseInt(user.getUserId().toString()));
                onshelvesEntity.setLastuser(Integer.parseInt(user.getUserId().toString()));

                onshelvesEntity.setRemark("");
                onshelvesEntity.setStatu(0);
                //onshelvesEntity.setNum(count);
                //onshelvesEntity.setCost(new BigDecimal(price));


                int type = 0;
                int count = 0;
                BigDecimal cost = new BigDecimal(0);
                for(IntelReplenEntity ir:rows){
                    ProductshelvesstcokEntity list = productshelvesstcokService.getByProductIdAndShelvesId(ir.getId(),gs.getId());
                    ProductEntity productEntity = productService.getById(ir.getId());
                    if(list!=null && ir.getUpperLimit()>list.getStock()){//库存小于库存预警上限，智能补货
                        if(onshelvesEntity.getId()==null){
                            onshelvesService.save(onshelvesEntity);
                        }
                        OnshelvesitemEntity onshelvesitemEntity = new OnshelvesitemEntity();
                        onshelvesitemEntity.setProductid(ir.getId());
                        onshelvesitemEntity.setOncount(ir.getUpperLimit()-list.getStock());
                        onshelvesitemEntity.setOnshelvesid(onshelvesEntity.getId());
                        onshelvesitemEntity.setCostprice(productEntity.getCostprice());
                        onshelvesitemEntity.setSellprice(productEntity.getSellprice());
                        onshelvesitemEntity.setTotalcost(new BigDecimal(ir.getUpperLimit()-list.getStock()).multiply(productEntity.getCostprice()));
                        onnshelvesitemService.save(onshelvesitemEntity);
                        type++;
                        count = count+(ir.getUpperLimit()-list.getStock());
                        cost = cost.add(new BigDecimal(ir.getUpperLimit()-list.getStock()).multiply(productEntity.getCostprice()));
                    }

                }
                if(onshelvesEntity.getId()!=null) {
                    onshelvesEntity.setType(type);
                    onshelvesEntity.setNum(count);
                    onshelvesEntity.setCost(cost);
                    onshelvesService.updateById(onshelvesEntity);
                }
            }
        }

        return R.ok();
    }


    /**
     * 导出补货数据
     * @return
     */
    @RequestMapping("/exportIntelReplen")
    @RequiresPermissions("sys:intelreplen:exportIntelReplen")
    public String exportIntelReplen(@RequestBody String parameterMap){
        JSONObject json = JSONObject.fromObject(parameterMap);
        String name = null;
        if(json.get("name")!=null&&!json.get("name").equals("null")){
            name = json.get("name").toString();
        }
        String categoryid = null;
        if(json.get("categoryid")!=null&&!json.get("categoryid").equals("null")){
            categoryid = json.get("categoryid").toString();
        }
        Integer shelvesid = 0;
        String sheleves = "全部货架";
        if(json.get("shelvesid")!=null&&!json.get("shelvesid").equals("null")){
            shelvesid = Integer.parseInt(json.get("shelvesid").toString());
            GoodshelvesEntity goodshelves = goodshelvesService.getById(shelvesid);
            sheleves = goodshelves.getShelvesname();
        }
        String str = "";
        try {
            List<IntelReplenEntity> rows = intelreplenService.queryList(name,categoryid,shelvesid);
            str = setUpExcelRank(rows,sheleves);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }

    public String setUpExcelRank(List<IntelReplenEntity>  list,String shelvesname){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
        String[] headers = { "货架名称", "条形码","库存下限","库存上限","当前库存","待上架库存","建议采购量","成本价","总金额"};
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet();
        //设置列宽
        sheet.setDefaultColumnWidth((short) 18);
        //创建第一行的对象，第一行一般用于填充标题内容。从第二行开始一般是数据
        HSSFRow row1 = sheet.createRow(0);
        HSSFCell cell1 = row1.createCell(0);
        HSSFRichTextString richString1 =  new HSSFRichTextString("货架：");
        cell1.setCellValue(richString1);


        HSSFCell cell2 = row1.createCell(1);
        HSSFRichTextString richString2 =  new HSSFRichTextString(shelvesname);
        cell2.setCellValue(richString2);

        HSSFCell cell3 = row1.createCell(3);
        HSSFRichTextString richString3 =  new HSSFRichTextString("补货方式：");
        cell3.setCellValue(richString3);

        HSSFCell cell4 = row1.createCell(4);
        HSSFRichTextString richString4 =  new HSSFRichTextString("补至库存上限");
        cell4.setCellValue(richString4);

        HSSFCell cell5 = row1.createCell(7);
        HSSFRichTextString richString5 =  new HSSFRichTextString("日期：");
        cell5.setCellValue(richString5);

        HSSFCell cell6 = row1.createCell(8);
        HSSFRichTextString richString6 =  new HSSFRichTextString(format.format(new Date()));
        cell6.setCellValue(richString6);


        HSSFRow row = sheet.createRow(1);
        for (short i = 0; i < headers.length; i++) {
            //创建单元格，每行多少数据就创建多少个单元格
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            //给单元格设置内容
            cell.setCellValue(text);
        }

        //遍历集合，将每个集合元素对象的每个值填充到单元格中
        for(int i=0;i<list.size();i++){
            IntelReplenEntity entity=list.get(i);
            //从第二行开始填充数据
            row = sheet.createRow(i+2);
            //该集合只记录数量和时间，这两个值来自statisticsModel。如果对象比较复杂，需要额外转换，比如Date类型的日期，int，float类型的数值
            List<String> datas=new ArrayList<>();

            String productname = entity.getProductname();
            String barcode = entity.getBarcode();
            String lowerLimit = entity.getLowerLimit().toString();
            String upperLimit = entity.getUpperLimit().toString();
            String stock = entity.getStock().toString();
            String onshelves = entity.getOnshelves().toString();
            String buycount = entity.getBuycount().toString();
            String avgcost = entity.getAvgcost().toString();
            String totalcost = entity.getTotalcost().toString();
            datas.add(productname);
            datas.add(barcode);
            datas.add(lowerLimit);
            datas.add(upperLimit);
            datas.add(stock);
            datas.add(onshelves);
            datas.add(buycount);
            datas.add(avgcost);
            datas.add(totalcost);
            for (int j=0;j<datas.size();j++) {
                String string=datas.get(j);
                HSSFCell cell = row.createCell(j);
                HSSFRichTextString richString = new HSSFRichTextString(string);
                HSSFFont font3 = workbook.createFont();
                //定义Excel数据颜色，这里设置为蓝色
                font3.setColor(HSSFColor.BLUE.index);
                richString.applyFont(font3);
                cell.setCellValue(richString);
            }

        }
        String message = "";
        File desktopDir = FileSystemView.getFileSystemView()
                .getHomeDirectory();
        String desktopPath = desktopDir.getAbsolutePath();
        try {
            FileOutputStream fout = new FileOutputStream(desktopPath+"/"+shelvesname+"补货计划_"+sdf.format(new Date())+".xls");
            workbook.write(fout);
            message = "/"+shelvesname+"补货计划_"+sdf.format(new Date())+".xls成功,请到桌面查找！";
            fout.close();
        } catch (Exception e) {
            e.printStackTrace();
            message = "导出失败！";
        }

        return message;
    }

}
